﻿using ZyGames.DZPocker.Model;
using ZyGames.Framework.Game.Contract;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Tools;
using ZyGames.Framework.Common.Serialization;
using System;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 玩家申请上局回顾
	/// </summary>
	public class Action30048 : BaseAction
	{
		private int tableId;
		private int userId;

		private TableData _currentTable;
		private GameUser _currentGameUser;
		private string _recordStr = string.Empty;
		private string _tableCardsStr = string.Empty;
		private string _userCardsStr = string.Empty;
		private string _userWinChipStr = string.Empty;
		private int _formalHand = 0;
		private int savedCount = 0;

		public Action30048(HttpGet actionGetter)
			: base((short)ActionType.DZApplyReview, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableId", ref tableId) &&
				httpGet.GetInt("UserId", ref userId))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			_currentTable = GameRoom.Current.GetTableData(tableId);
			if (_currentTable == null)
			{
				Tool.WriteWarmingLine("消息30048获得房间不存在");
				return false;
			}
			if (_currentTable.State == TableState.Countdown || _currentTable.State == TableState.WaitCheck)
			{
				Tool.WriteErrorLine("消息30048 请求牌局回顾当前正在倒计时或者退出时间不能退出");
				return false;
			}
			_currentGameUser = GameTable.Current.GetUser(userId);
			if (_currentGameUser == null)
			{
				Tool.WriteWarmingLine("消息30048玩家不存在");
				return false;
			}
			var tableCards = _currentTable.GetFormalTableCards();
			var formalRecords = _currentTable.GetFormalUserBetRecord();
			if(formalRecords.Count < 1)
			{
				Tool.WriteErrorLine("消息30048 没有保存玩家下注记录");
				return false;
			}
			var handId = formalRecords[0].Hand;
			this._recordStr = Convert.ToBase64String(ProtoBufUtils.Serialize(formalRecords));  //List<SharedUserBetRecords>
			this._tableCardsStr = Convert.ToBase64String(ProtoBufUtils.Serialize(tableCards));  //SharedTableCards
			this._userCardsStr = Convert.ToBase64String(ProtoBufUtils.Serialize(_currentTable.GetFormalUserCards()));  //Dictionary<SimpleUserData, List<int>>
			this._userWinChipStr = Convert.ToBase64String(ProtoBufUtils.Serialize(_currentTable.GetFormalUsersScore())); //上局玩家获胜的筹码  包括保险人 也包括输掉的人

			this._formalHand = formalRecords[0].Hand;
			this.savedCount = GameTable.Current.UserSavedCount(userId);

			return true;
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this._currentTable.TableLogicID);
			this.PushIntoStack(this._formalHand);
			this.PushIntoStack(this._recordStr);
			this.PushIntoStack(this._tableCardsStr);
			this.PushIntoStack(this._userCardsStr);
			this.PushIntoStack(this._userWinChipStr);
			this.PushIntoStack(this.savedCount);
		}
	}
}
